package com.icehelper.hades.base.util;

import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;

/**
 * springutil
 *
 * @Author: Leon Sun
 * @create 2020-11-21 12:09 PM
 **/

public class SpringUtil {


    /**
     * 修改bean
     *
     * @param applicationContext Spring 上下文
     * @param targetBeanName     目标Bean对象
     * @param targetFieldName    目标属性名称
     * @param targetField        目标属性
     */
    public static void modifyBean(ApplicationContext applicationContext,
                                  String targetBeanName, String targetFieldName, Object targetField) {
        try {
            String[] beanNames = applicationContext.getBeanDefinitionNames();
            for (String beanName : beanNames) {
                //如果类型为空 或者 不是要修改的类，跳过
                Class<?> beanType = applicationContext.getType(beanName);
                if (beanType == null || !targetBeanName.equals(beanName)) {
                    continue;
                }

                Object bean = applicationContext.getBean(beanName);
                //获取要修改的类的所有属性
                Field[] declaredFields = beanType.getDeclaredFields();
                for (Field field : declaredFields) {
                    field.setAccessible(true);

                    //如果属性名称匹配
                    if (field.getName().equals(targetFieldName)) {
                        field.set(bean, targetField);
                    }
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
